#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

int add(int a, int b){
    return a + b;
}
int sub(int a, int b){
    return a - b;
}
int multiply(int a, int b){
    return a * b;
}
int divide(int a, int b){
    return a / b;
}
#if 0
C语言的写法
int calculate(int a, string operation, int b){
    //定义一个函数指针
    //c++中的主要这一点和c语言是有区别的
    //可以将函数像对象一样去组织
    int (*pFunc)(int,int);
    if(operation == "+"){
        pFunc = add;
    }else if(operation == "-"){
        pFunc = sub;
    }else if(operation == "*"){
        pFunc = multiply;
    }else if(operation == "/"){
        pFunc = divide;
    }else {
        cout << "operation error";
        return 0;
    }
    return pFunc(a, b);
}
#endif
int calculate(int a, string operation, int b){
    //定义一个函数指针
    //c++中的主要这一点和c语言是有区别的
    //可以将函数像对象一样去组织
    typedef int (*FunctionPointer)(int,int);
    //像类和对象一样去组织
    //前面是类 后面是类的实例化对象
    FunctionPointer fp;
    if(operation == "+"){
        fp = add;
    }else if(operation == "-"){
        fp = sub;
    }else if(operation == "*"){
        fp = multiply;
    }else if(operation == "/"){
        fp = divide;
    }else {
        cout << "operation error";
        return 0;
    }
    return fp(a, b);
}

void test(){
    cout << calculate(10, "+", 20) << endl;
    cout << calculate(10, "-", 20) << endl;
    cout << calculate(10, "*", 20) << endl;
    cout << calculate(40, "/", 20) << endl;
}

int main()
{
    test();
    return 0;
}

